<?php
namespace Weiserver\Controller;
use Common\Controller\BaseController;
class LoginController extends BaseController {
	
	/**
	*	初始化方法
	*/
	protected function _initialize(){
		parent::_initialize();
	}
	
	/**
	*	微信服务器交互服务
	*/
	public function index(){
		
		//$code=I('get.code');
		$code=$_GET['code'];
		$state=I('get.state');
		
		if(!empty($code)){
			$appid='wxc68d67067803a88d';
			$appsecret='69f02bd9a8eeffbd9c606c8a99cd3475';
			$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code";
			$ch=curl_init();

			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_TIMEOUT, 30);
			$result=curl_exec($ch);
			echo(curl_error($ch));
			//curl_close($ch);
			
			$hisen=json_decode ($result,TRUE); // 解析json
			if(isset($hisen['access_token'])&!empty($hisen['access_token'])){
				
				$access_token=$hisen['access_token'];
				$openid=$hisen['openid'];
				
				$_SESSION['access_token']=$access_token;
				$_SESSION['openid']=$openid;
				
				//echo $_SESSION['openid'];
				//echo $_SESSION['access_token'];
				
				$url="https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN";
				curl_setopt($ch, CURLOPT_URL, $url);
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_TIMEOUT, 30);
				$result=curl_exec($ch);
				echo(curl_error($ch));
				curl_close($ch);
				
				$hisen=json_decode ($result,TRUE); // 解析json
				
				$nickname=$hisen['nickname'];
				$sex=$hisen['sex'];
				$city=$hisen['city'];
				$province=$hisen['province'];
				$headimgurl=$hisen['headimgurl'];
				
				$_SESSION['nickname']=$nickname;
				$_SESSION['sex']=$sex;
				$_SESSION['city']=$city;
				$_SESSION['province']=$province;
				$_SESSION['headimgurl']=$headimgurl;
				
			}
			

			
			//print_r($_SESSION);
		}
		//echo $state;
		echo '<br>';
		//echo $url;
		//echo $code;
		//echo '你好';
	}
	
	public function logout(){
		session_destroy();
		print_r($_SESSION);
	}
	
}